package com.jxzyk.model.know;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.core.entity.I_List;
import com.core.entity.params.MapParams;
import com.core.entity.params.ReqParams;
import com.core.ui.fragment.BaseFragment;
import com.core.util.T;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jxzyk.R;
import com.jxzyk.adapter.KnowAdapter;
import com.jxzyk.config.API;
import com.jxzyk.entity.QAList;
import com.jxzyk.entity.User;
import com.jxzyk.http.BaseRequest.OnDialogListener;
import com.jxzyk.http.Query;
import com.jxzyk.http.req.KnowRequest;
import com.jxzyk.model.EditActivity;
import com.jxzyk.model.SearchActivity;
import com.jxzyk.util.UserManger;
import com.jxzyk.view.TitleLayout;
import com.jxzyk.view.TitleLayout.OnPopupWindowListener;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

public class KnowFragment extends BaseFragment {
	@ViewInject(R.id.title)
	TitleLayout title;
	@ViewInject(R.id.list_know)
	PullToRefreshListView mPullRefreshListView;

	private ListView listView;
	public static int position = 0;

	UserManger manger;

	@Override
	public void initData(Bundle bundle) {
		manger = new UserManger(getContext());
	}

	@Override
	public int initUiRes() {
		return R.layout.fra_know;
	}

	@Override
	public void initUi(View view) {
		initTitle();
		mPullRefreshListView
				.setOnRefreshListener(new OnRefreshListener<ListView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {
						String label = DateUtils.formatDateTime(getActivity()
								.getApplicationContext(), System
								.currentTimeMillis(),
								DateUtils.FORMAT_SHOW_TIME
										| DateUtils.FORMAT_SHOW_DATE
										| DateUtils.FORMAT_ABBREV_ALL);
						// Update the LastUpdatedLabel
						refreshView.getLoadingLayoutProxy()
								.setLastUpdatedLabel(label);
						try {
							loadList(0, position);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});
		// Add an end-of-list listener
		mPullRefreshListView
				.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

					@Override
					public void onLastItemVisible() {
						try {
							loadList(page, position);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});
		listView = mPullRefreshListView.getRefreshableView();
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Bundle bundle = new Bundle();
				try {
					QAList qaList = (QAList) lists.get(arg2 - 1);
					bundle.putSerializable(qaList.getClass().getName(), qaList);
					showActivity(KnowActivity.class, bundle);
				} catch (Exception e) {
					e.printStackTrace();
					T.toast("下标越界[listsize]" + lists.size() + "[index]" + arg2);
				}
			}
		});
		try {
			loadList(page, position);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private String[] titles = new String[] { "知道", "我的问题", "我的回答" };

	private void initTitle() {
		title.setTtile(titles[0]);
		// 加载数据
		List<String> groups = new ArrayList<String>();
		for (int i = 0; i < titles.length; i++) {
			groups.add(titles[i]);
		}
		title.setPopupWindowListener(groups, new OnPopupWindowListener() {

			@Override
			public void onClick(int position) {
				// CourseType courseType = (CourseType) data.get(position);
				// type = courseType.getType_id();
				title.setTtile(titles[position]);
				try {
					loadList(0, position);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		title.setOnLeftListener(R.drawable.ic_write, new OnClickListener() {

			@Override
			public void onClick(View v) {
				Bundle bundle = new Bundle();
				bundle.putString(EditActivity.class.getName(), API.QA.publish);
				// showActivity(EditActivity.class, bundle);
				Intent intent = new Intent(getActivity(), EditActivity.class);
				intent.putExtras(bundle);
				startActivityForResult(intent, 1);
			}
		});
		title.setOnRightListener(R.drawable.ic_search, new OnClickListener() {

			@Override
			public void onClick(View v) {
				Bundle bundle = new Bundle();
				bundle.putString(SearchActivity.class.getName(), API.QA.list);
				showActivity(SearchActivity.class, bundle);
				// T.toast("搜索");
			}
		});
	}

	private List<I_List> lists = new ArrayList<>();
	private KnowAdapter adapter = null;
	private int page = 0;

	private void loadList(int my_page, int position) throws Exception {
		KnowFragment.position = position;
		String url = "";
		Query query = new Query();
		query.setPage(my_page);
		query.setLength(5);
		ReqParams params = new MapParams();
		User user = manger.getUser();
		params = query.toParams();
		switch (position) {
		case 0:// 知道
			url = API.QA.list;
			break;
		case 1:// 我的问题
			url = API.QA.list_user;
			params.put("userid", user.getUser_id());
			break;
		case 2:// 我的回答
			url = API.QA.list_qa;
			params.put("userid", user.getUser_id());
			break;
		// case 3:// 收藏问题
		// url = API.QA.
		// break;
		default:
			break;
		}
		KnowRequest request = new KnowRequest(getActivity(), url);
		request.setParams(params);
		if (my_page == 0) {
			page = my_page;
			lists.clear();
			if (adapter == null) {
				adapter = (KnowAdapter) new KnowAdapter().instance(
						getActivity(), lists);
				listView.setAdapter(adapter);
			}
		}
		request.setOnDialogListener(new OnDialogListener() {

			@Override
			public void onSuccess(JSONObject json) {
				try {
					JSONArray array = json.getJSONArray("data");
					if (array.size() > 0) {
						for (int i = 0; i < array.size(); i++) {
							QAList qaList = (QAList) new QAList()
									.instance(array.getJSONObject(i));
							lists.add(qaList);
						}
						adapter.notifyDataSetChanged();
						page++;
					}
					// Call onRefreshComplete when the list has been refreshed.
					mPullRefreshListView.onRefreshComplete();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(String msg) {
				// Call onRefreshComplete when the list has been refreshed.
				adapter.notifyDataSetChanged();
				mPullRefreshListView.onRefreshComplete();
				// if (page == 0) {
				// T.toast("数据为空");
				// }
			}
		});
		if (page == 0) {
			request.show();
		} else {
			request.start();
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 1:
			try {
				loadList(0, position);
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;

		default:
			break;
		}
	}

}
